<template>
	<view class="container">
		<!-- 状态栏 -->
		<view class="status-bar">
			<text>单位：{{ currentUnit }}｜性别：{{ gender }}｜年龄：{{ healthData.age || '未设置' }}</text>
		</view>

		<!-- 主输入区 -->
		<view class="input-section">
			<input class="main-input" type="number" v-model="healthData[currentType]"
				:placeholder="`请输入${currentLabel}（${currentUnit}）`" />

			<!-- 输入类型切换 -->
			<view class="type-buttons">
				<button v-for="t in inputTypes" :key="t.value"
					:class="['type-btn', { active: currentType === t.value }]" @click="switchType(t.value)">
					{{ t.label }}
				</button>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-section">
			<button class="action-btn" @click="toggleUnit">切换单位</button>
			<button class="action-btn" @click="toggleGender">切换性别</button>
			<button class="action-btn" @click="calculate">计算体脂率</button>
		</view>

		<!-- 结果展示 -->
		<view v-if="result" class="result-section">
			<text class="result-text">体脂率：{{ result }}%</text>
			<text class="result-advice">{{ healthAdvice }}</text>
		</view>

		<!-- 历史记录弹窗 -->
		<uni-popup ref="historyPopup" type="bottom">
			<view class="history-popup">
				<view class="popup-header">
					<text>测量记录</text>
					<button @click="clearHistory">清空</button>
				</view>
				<scroll-view scroll-y class="history-list">
					<view v-for="(item, index) in history" :key="item.timestamp" class="history-item">
						<text>记录 #{{ index + 1 }} {{ formatDate(item.timestamp) }}</text>
						<text>{{ item.bfp }}%</text>
						<text>{{ item.gender }}｜{{ item.unit }}</text>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentType: 'height', // 当前输入类型
				gender: '男', // 性别
				unit: 'metric', // 单位制
				result: null, // 计算结果
				healthData: { // 健康数据
					height: null,
					weight: null,
					age: null
				},
				history: [], // 历史记录
				inputTypes: [ // 输入类型配置
					{
						label: '身高',
						value: 'height'
					},
					{
						label: '体重',
						value: 'weight'
					},
					{
						label: '年龄',
						value: 'age'
					}
				]
			};
		},
		computed: {
			// 当前输入标签
			currentLabel() {
				return this.inputTypes.find(t => t.value === this.currentType)?.label || '';
			},
			// 当前单位显示
			currentUnit() {
				if (this.currentType === 'age') return '岁';
				return this.unit === 'metric' ?
					(this.currentType === 'height' ? '厘米' : '千克') :
					(this.currentType === 'height' ? '英寸' : '磅');
			},
			// 健康建议
			healthAdvice() {
				if (!this.result) return '';
				const ranges = this.gender === '男' ? {
					low: 5,
					normal: 14,
					high: 25
				} : {
					low: 13,
					normal: 21,
					high: 30
				};

				if (this.result < ranges.low) return '体脂过低，建议增加营养摄入';
				if (this.result > ranges.high) return '体脂过高，建议加强锻炼';
				return this.result <= ranges.normal ? '体脂健康，请保持' : '体脂偏高，建议注意饮食';
			}
		},
		methods: {
			// 切换输入类型
			switchType(type) {
				this.currentType = type;
			},
			// 切换单位制
			toggleUnit() {
				this.unit = this.unit === 'metric' ? 'imperial' : 'metric';
			},
			// 切换性别
			toggleGender() {
				this.gender = this.gender === '男' ? '女' : '男';
			},
			// 计算体脂率（BMI法）
			calculate() {
				if (!this.validateInput()) return;

				// 单位转换
				const height = this.unit === 'metric' ?
					this.healthData.height :
					this.healthData.height * 2.54;
				const weight = this.unit === 'metric' ?
					this.healthData.weight :
					this.healthData.weight * 0.453592;

				// BMI计算
				const bmi = weight / ((height / 100) ** 2);

				// 体脂率公式（简化版）
				this.result = this.gender === '男' ?
					(1.2 * bmi + 0.23 * this.healthData.age - 16.2).toFixed(1) :
					(1.2 * bmi + 0.23 * this.healthData.age - 5.4).toFixed(1);

				this.saveHistory();
			},
			// 输入验证
			validateInput() {
				const data = this.healthData[this.currentType];
				if (!data || isNaN(data)) {
					uni.showToast({
						title: '请输入有效数值',
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			// 保存记录
			saveHistory() {
				this.history.unshift({
					bfp: this.result,
					gender: this.gender,
					unit: this.unit,
					timestamp: Date.now()
				});
			},
			// 清空记录
			clearHistory() {
				this.history = [];
				uni.showToast({
					title: '记录已清空',
					icon: 'success'
				});
			},
			// 日期格式化
			formatDate(timestamp) {
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 20px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.status-bar {
		margin-bottom: 20px;
		color: #666;
		font-size: 14px;
	}

	.input-section {
		background: white;
		border-radius: 8px;
		padding: 15px;
		margin-bottom: 20px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	.main-input {
		height: 50px;
		font-size: 18px;
		border-bottom: 1px solid #eee;
		margin-bottom: 15px;
	}

	.type-buttons {
		display: flex;
		gap: 10px;
	}

	.type-btn {
		flex: 1;
		background: #f0f0f0;
		border: none;
		color: #666;
	}

	.type-btn.active {
		background: #007AFF;
		color: white;
	}

	.action-section {
		display: flex;
		gap: 10px;
		margin-bottom: 20px;
	}

	.action-btn {
		flex: 1;
		background: #007AFF;
		color: white;
	}

	.result-section {
		background: white;
		padding: 20px;
		border-radius: 8px;
	}

	.result-text {
		font-size: 24px;
		color: #007AFF;
		display: block;
		text-align: center;
		margin-bottom: 10px;
	}

	.result-advice {
		color: #666;
		display: block;
		text-align: center;
	}

	.history-popup {
		background: white;
		padding: 20px;
		border-radius: 16px 16px 0 0;
	}

	.history-item {
		padding: 15px 0;
		border-bottom: 1px solid #eee;
		display: flex;
		justify-content: space-between;
	}
</style>